/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2013 www.pretty-tools.com
 */

var logger = yrprxFactory.createLogger("wsshContentScript");

var initialized = false;

function initialize()
{
    if (initialized)
        return;

    initialized = true;

    logger.debug("initializing...");

    if (document.location.href.indexOf("webslideshow-autostart") != -1) // run slide show
        startSlideShow();

    searchMagicElements();

    logger.debug("initialized");
}

function startSlideShow()
{
    try
    {
        var images = g_wsshImageResolver.getImages(document);
        if (images && images.length)
            wsshWindowManager.openSlideShow(images, document.title);
        else //TODO: think about this
            yrprxPrompt.alert(wsshResources["webslideshow.title"], wsshResources["webslideshow.can.not.find.appropriate.images"]);
    }
    catch(ex)
    {
        if (logger.enabled) logger.error("startSlideShow: ", ex);
    }
}

function findImages()
{
    var response = {images: [], title: document.title};
    try {
        response.images = g_wsshImageResolver.getImages(document);
        if (logger.enabled) logger.debug("findImages: found images: " + response.images.length);
    } catch(ex) {
        if (logger.enabled) logger.error("findImages: ", ex);
    }
    return response;
}

function openImageLinkFullScreen(image)
{
    try
    {
        if (wsshConfig.fullscreenImageLink)
        {
            wsshWindowManager.openSlideShow([image]);
            return false;
        }
    }
    catch(ex)
    {
        if (logger.enabled) logger.error("openImageLinkFullScreen: ", ex);
    }
    return true;
}

function openRuledImageFullScreen(image)
{
    try
    {
        if (wsshConfig.fullscreenRuledImages)
        {
            wsshWindowManager.openSlideShow([image]);
            return false;
        }
    }
    catch(ex)
    {
        if (logger.enabled) logger.error("openRuledImageFullScreen: ", ex);
    }
    return true;
}

function searchMagicElements()
{
    try
    {
        var startSlideShow = function(event) {
            event.stopPropagation();
            window.startSlideShow();
        };

        var fullscreenDirectLink = function(event) {
            event.stopPropagation();
            return window.openImageLinkFullScreen(this.href);
        };

        yrprxHTMLContentHelper.enumerateElementsByTagName(document, "a", function(elem) {
            try
            {
                if ("webslideshow-start" == elem.className)
                {
                    elem.onclick = startSlideShow;
                    elem.href = "javascript: void(0);";
                }
                else if ("webslideshow-rules" == elem.className)
                {
                    var rulesURL = elem.href;
                    elem.onclick = function(event) {
                        event.stopPropagation();
                        wsshWindowManager.openImportRules(rulesURL);
                    };
                    elem.href = "javascript: void(0);";
                }
                else if (g_wsshImageResolver.isDirectImageLink(elem.href))
                {
                    if (!elem.onclick) // do not replace default behavior
                        elem.onclick = fullscreenDirectLink;
                }
            }
            catch(ex)
            {
                if (logger.enabled) logger.error("searchMagicElements: Exception in 'A' handler: " + ex);
            }
        });

        var buttonsHandler = function(elem) {
            try
            {
                if ("webslideshow-start" != elem.className || elem.tagName == "INPUT" && elem.type != "button")
                    return;

                elem.onclick = startSlideShow;
            }
            catch(ex)
            {
                if (logger.enabled) logger.error("searchMagicElements: Exception in handler: " + ex);
            }
        };

        yrprxHTMLContentHelper.enumerateElementsByTagName(document, 'input', buttonsHandler);
        yrprxHTMLContentHelper.enumerateElementsByTagName(document, 'button', buttonsHandler);

        if (wsshConfig.fullscreenRuledImages)
        {
            var ruledElements = g_wsshImageResolver.getSatisfiedElements(document);
            for (var j in ruledElements)
            {
                var elem = ruledElements[j].elem;
                if (!elem) continue;

                if (elem.tagName == "IMG" && g_wsshImageResolver.isParentALink(elem))
                    elem = elem.parentNode;

                if (!elem.onclick) // do not replace default behavior
                    createOnClickEventForRuledElement(elem, ruledElements[j].url);
            }
        }

//        if (wsshConfig.useSubscriptions)
//        {
//            var subscription = document.getElementById("WebSlideShow-Subscription");
//            if (subscription) wsshRulesUpdateManager.checkForSubscriptionUpdate(subscription.value);
//        }
    }
    catch(ex)
    {
        if (logger.enabled) logger.error("searchMagicElements: ", ex);
    }
}

function createOnClickEventForRuledElement(elem, url)
{
    elem.onclick = function(event) {
        event.stopPropagation();
        return openRuledImageFullScreen(url);
    };
}

var numberOfImages = null;

function getImagesCount(force, cfg, items)
{
    if (numberOfImages == null || force)
    {
        numberOfImages = null;

        if (cfg)
            wsshConfig.copyFrom(cfg);

        if (g_wsshImageResolver._items == null || force)
        {
            if (!items)
            {
                logger.debug("getImagesCount: NotYetInitialized");
                return "NotYetInitialized";
            }
            else
            {
                if (logger.enabled) logger.debug("getImagesCount: initialize ImageResolver with items: " + items.length);
                g_wsshImageResolver.initializeItems(items);
            }
        }

        numberOfImages = g_wsshImageResolver.getImages(document, true);
    }

    if (logger.enabled) logger.debug("getImagesCount: number of images: " + numberOfImages);

    return numberOfImages;
}
